package com.star.modules.sys.api;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.mapper.BeanMapper;
import com.star.modules.sys.base.BizDataResult;
import com.star.modules.sys.entity.ShQuestion;
import com.star.modules.sys.enums.ResultEnum;
import com.star.modules.sys.excetion.ApiException;
import com.star.modules.sys.service.ShQuestionService;
import com.star.modules.sys.vo.QuestionVo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 问题接口
 */
@RestController
@RequestMapping(value = "${frontPath}/sys/question")
public class QuestionController {

    @Autowired
    private ShQuestionService shQuestionService;

    public final static int RANDOM_QUESTION_NUM = 5;
    /**
     * 随机 RNADOM_QUESTION_NUM 个问题
     * @return
     */
    @RequestMapping(value = "random")
    public BizDataResult getRandom(){
        List<QuestionVo>  questionVos = ListUtils.newArrayList();
        try{
            ShQuestion question = new ShQuestion();
            question.setStatus(ShQuestion.STATUS_NORMAL);
            List<ShQuestion>  shQuestions = shQuestionService.findList(question);
            if(shQuestions.size() < RANDOM_QUESTION_NUM){//问题数量不足
                questionVos = BeanMapper.mapList(shQuestions,QuestionVo.class);
            }else {//问题数量充足开始 ，随机取
                int next = RandomUtils.nextInt(0,shQuestions.size());
                while (questionVos.size() < RANDOM_QUESTION_NUM){
                    int now =  RandomUtils.nextInt(0,shQuestions.size());
                    if(next == now){
                        continue;
                    }else {
                        questionVos.add(BeanMapper.map(shQuestions.get(now),QuestionVo.class));
                        next = now;
                    }
                }
            }
        }catch (Exception e){
            throw new ApiException(e);
        }
        return BizDataResult.createResult(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),questionVos);
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @RequestMapping(value = "detail")
    public BizDataResult getQuestionDetail(String id){
        QuestionVo questionVo = null;
        try{
            questionVo = BeanMapper.map(shQuestionService.get(id),QuestionVo.class);
        }catch (Exception e){
            throw new ApiException(e);
        }
        return BizDataResult.createResult(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),questionVo);
    }
}
